<template>
    <div>
        <van-nav-bar left-arrow>
            <template #title>
                <van-search v-model="keyword" shape="round" placeholder="请输入搜索关键词" />
            </template>
            <template #right>
                <span @click="searchFn">搜索</span>
            </template>
        </van-nav-bar>
        <!-- 内容 -->
        <div class="content">
            <h1>历史记录</h1>
            <ul class="content-list">
                <li v-for="(item,index) in history" :key="index" @click="historySearch(item)" >{{item}}</li>
            </ul>
        </div>
        <div class="content">
            <h1>搜索结果</h1>
            <ul class="content-list search-box">
                <li v-for="item in searchList" :key="item.id"
                v-html="item.title.replace(keyword, `<span class='red'>${keyword}</span>` )"
                @click="$router.push({path: '/articleDetail',query: { id: item.id} })">
                    <!-- {{ item.title }} -->
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
import { post_search } from "@/api/news"
export default {
    data(){
        return {
            keyword: "",
            searchList: [],
            history: JSON.parse(localStorage.getItem("75-history"))||[]
        }
    },
    methods: {
        historySearch(val){
            this.keyword = val;
            this.searchFn()
        },
        searchFn(){
            if(!this.keyword){return this.$toast.fail('请输入关键词搜索!')}
            // 利用indexOf方法查找数组中是否已经存在搜索关键词，如果不存在则加入
            if(this.history.indexOf(this.keyword) == -1){
                this.history.push(this.keyword)
                // 数组去重
                // this.history =  [...new Set(this.history)]
                localStorage.setItem("75-history", JSON.stringify(this.history))
            }

            post_search({
                keyword: this.keyword
            }).then(res=>{
                this.searchList = res.data.data
                // 注意：关键词不能清空，因为清空之后，关键词标红就没有效果了
            })
        }
    }
}
</script>

<style lang="less" scoped>
/deep/.red{
    color: red;
}
/deep/.van-nav-bar{
    border-bottom: 1px solid #ddd;
    .van-icon{
        color: #000;
    }
    .van-search{
        padding: 0px 12px;
    }
}
.content{
    padding: 20px 10px;
    border-bottom: 1px solid #ddd;
    h1{
        font-size: 20px;
        font-weight: bold;
        margin: 10px 0;
    }
    .content-list{
        li{
            font-size: 16px;
        }
    }
    .search-box{
        li{
            text-decoration: underline;
            margin: 10px 0;
        }
    }
}
</style>